package com.ruoyi.quartz.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.domain.SysEmail;
import com.ruoyi.quartz.service.ISyncEmailsService;
import com.ruoyi.quartz.service.ISysEmailService;
import com.ruoyi.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class SyncEmailsServiceImpl implements ISyncEmailsService {

    private final static Logger logger = LoggerFactory.getLogger("sync-email");
    @Autowired
    private ISyncEmailsService syncEmailsService;
    @Autowired
    private ISysEmailService sysEmailService;
    @Autowired
    private ISysDeptService sysDeptService;

    @Override
    public String getQqEmailToken() {
        String content = HttpUtil.get("https://api.exmail.qq.com/cgi-bin/gettoken?corpid=wm2255026ca5707fdc&corpsecret=CulrckhBYtHPZnfXOsbyI3bc7C58SpsG3dVbndunEMLIYHNNDa4bKfeq2doBTFad");
        logger.debug("获取腾讯企业邮箱token:"+content);
        JSONObject result = JSONObject.parseObject(content);
        if(result.getString("errcode").equals("0")){
            logger.debug("获取腾讯企业邮箱token:"+result.getString("access_token"));
            return result.getString("access_token");
        }else{
            logger.debug("获取腾讯企业邮箱token失败");
            return null;
        }
    }
    @Override
    public void checkQqEmailInfo(JSONArray emailAccounts) {
        String qqEmailToken = this.getQqEmailToken();
        for (int i = 0; i < emailAccounts.size(); i++) {
            JSONObject email = emailAccounts.getJSONObject(i);
            if(StrUtil.isEmpty(email.getString("company_mail"))){
                continue;
            }
            String content = HttpUtil.get("https://api.exmail.qq.com/cgi-bin/user/get?access_token="+qqEmailToken+"&userid="+email.getString("company_mail"));
            logger.info("获取腾讯企业邮箱信息:"+content);
            JSONObject result = JSONObject.parseObject(content);
            if(result.getString("errcode").equals("0")){
                logger.debug("获取腾讯企业邮箱信息成功:"+result.toJSONString());
                if(email.getString("psn_status").equals("3") ||email.getString("psn_status").equals("12")||email.getString("psn_status").equals("4")//||email.getString("psn_status").equals("12")||email.getString("psn_status").equals("4")||email.getString("psn_status").equals("5")
                ){
                    //如果腾讯邮箱是启用，则禁用邮箱
                    if(result.getString("enable").equals("1")){
                        syncEmailsService.updateQqEmailInfo(qqEmailToken,result.getString("userid"),0);
                    }
                }else{
                    //如果腾讯邮箱是禁用，则启用邮箱
                    if(result.getString("enable").equals("0")){
                        syncEmailsService.updateQqEmailInfo(qqEmailToken,result.getString("userid"),1);
                    }
                }
            }
            if(result.getString("errcode").equals("60111")
                &&StrUtil.isNotEmpty(email.getString("company_mail"))
                &&!email.getString("psn_status").equals("3") &&!email.getString("psn_status").equals("12")&&!email.getString("psn_status").equals("4")
                ){
                logger.info("邮箱不存在新增邮箱"+email.getString("company_mail")+";dept_code:"+email.getString("dept_code")+";"+email.toJSONString());

                JSONArray deparments = this.searchDepartment(email.getString("dept_code"));
                if(deparments.size()>0){
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("access_token",qqEmailToken);
                    jsonObject1.put("userid",email.getString("company_mail"));
                    jsonObject1.put("name",email.getString("psn_name"));
                    jsonObject1.put("mobile",email.getString("phone"));
                    jsonObject1.put("department",deparments);
                    jsonObject1.put("password","Qwer@1234");
                    logger.info("新增邮箱json:" + jsonObject1.toJSONString());
                    this.insertQqEmailInfo(qqEmailToken,jsonObject1);
                }else{
                    logger.info("新增邮箱信息没有找到企业邮箱部门:" + email.toJSONString());
                }
            }
        }

    }

    public JSONArray searchDepartment(String deptId){
        logger.info("搜索腾讯企业邮箱部门开始:"+deptId);
        JSONArray deparments = new JSONArray();
        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        if(sysDept==null&&StringUtils.isEmpty(sysDept.getEmailDeptId())){
            logger.info("未找到企业邮箱对应的deptId:"+deptId);
            return deparments;
        }else{
            deparments.add(new Long(sysDept.getEmailDeptId()));
            return deparments;
        }
    }
    @Override
    public String updateQqEmailInfo(String token,String userId,int enable){
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("access_token",token);
        jsonObject1.put("userid",userId);
        jsonObject1.put("enable",enable);
        logger.info("更新腾讯企业邮箱开始:"+jsonObject1.toJSONString());
        String result2 = HttpRequest.post("https://api.exmail.qq.com/cgi-bin/user/update?access_token="+token)
                .body(jsonObject1.toJSONString())
                .execute().body();

        JSONObject result = JSONObject.parseObject(result2);
        //更新成功
        if(result.getString("errcode").equals("0")){
            //禁用
            if(enable==0){
                SysEmail sysEmail1 = sysEmailService.selectSysEmailById(userId);
                if(null==sysEmail1){
                    SysEmail sysEmail = new SysEmail();
                    sysEmail.setEmailId(userId);
                    sysEmail.setEmailName(userId);
                    sysEmail.setUpdateDate(new Date());
                    sysEmailService.insertSysEmail(sysEmail);
                }
            }
            //启用
            if(enable==1){
                sysEmailService.deleteSysEmailById(userId);
            }
            logger.info("更新腾讯企业邮箱结束:"+result2);
        }else{
            logger.error("更新腾讯企业邮箱出错"+result2);
        }
        return result2;
    }

    @Override
    public String insertQqEmailInfo(String token,JSONObject jsonObject){

        logger.info("创建腾讯企业邮箱开始:"+jsonObject);
        String result2 = HttpRequest.post("https://api.exmail.qq.com/cgi-bin/user/create?access_token="+token)
                .body(jsonObject.toJSONString())
                .execute().body();

        JSONObject result = JSONObject.parseObject(result2);
        if(result.getString("errcode").equals("0")){
            logger.info("创建腾讯企业邮箱结束:"+result2);
        }else{
            logger.error("创建腾讯企业邮箱出错"+result2);
        }
        return result2;
    }
    @Override
    public String deleteQqEmailInfo(String token,String email){
        String result2 ="";
        String content = HttpUtil.get("https://api.exmail.qq.com/cgi-bin/user/get?access_token="+token+"&userid="+email);
        logger.debug("获取腾讯企业邮箱信息:"+content);
        JSONObject result = JSONObject.parseObject(content);
        if(result.getString("errcode").equals("0")) {
            //如果腾讯邮箱是启用，则删除邮箱
            if(result.getString("enable").equals("1")){
                sysEmailService.deleteSysEmailById(email);
            }else if(result.getString("enable").equals("0")){
                logger.info("删除腾讯企业邮箱开始:" + email);
                String delContent = HttpUtil.get("https://api.exmail.qq.com/cgi-bin/user/delete?userid=" + email + "&access_token=" + token);
                JSONObject delResult = JSONObject.parseObject(delContent);
                if(delResult.getString("errcode").equals("0")) {
                    sysEmailService.deleteSysEmailById(email);
                }
                logger.info("删除腾讯企业邮箱结束:" + delContent);
            }else{
            }
        }else
        //如果邮箱已经被删除
        if(result.getString("errcode").equals("60111")){

            sysEmailService.deleteSysEmailById(email);
        }else{
            logger.error("删除腾讯企业邮箱出错"+content);
        }
        return result2;
    }

    @Override
    public JSONArray getHrUserList(int offset) {
        logger.debug("查询hr系统最近5分钟修改的用户开始:");
        HashMap<String, Object> paramMap = new HashMap<>();
        if(offset!=0){
            String updateDate = DateUtil.formatDateTime(DateUtil.offsetMinute(new Date(), offset));//当前时间偏移5分钟
            paramMap.put("updated_date", updateDate);
        }
        //测试 https://mdmuat.ganglongchina.com
        //测试 http://172.22.21.180:37080
        //生产 http://192.168.100.180
        JSONArray objects = new JSONArray();
        try {
            String users = HttpRequest.post("http://192.168.100.180/service/datapub/rest/api/v1/hcm/psnList")
                    .header("appKey", "glyx")//头信息，多个头信息多次调用此方法即可
                    .header("appSecret", "eyJhbGciOiJIUzUxMiJ9.eyJhcHBDb2RlIjoiZ2x5eCIsImV4cCI6MTkyMzU0NDYwMH0.NKSJBNYg9BXtk9gHkbRfqkGCBK77dtEk33N-bLq6c6XQk8lsvVRGMlPzq0zdRvp9MFKkKB8xm-SJ_efdNMYyCg")//头信息，多个头信息多次调用此方法即可
                    .form(paramMap)//表单内容
                    .timeout(10000)//超时，毫秒
                    .execute().body();
            JSONObject result = JSONObject.parseObject(users);

            logger.debug("查询hr系统最近修改的用户结束:"+result);
            if(result.getString("code").equals("2000")){
                objects=result.getJSONObject("data").getJSONArray("content");
            }
        }catch (Exception e){
            logger.error("查询hr系统最近修改的用户出错:"+e.getMessage());
        }finally {
            return objects;
        }

    }

    @Override
    public JSONArray getHrAllDeptList() {
        logger.info("同步部门数据开始:");
        HashMap<String, Object> paramMap = new HashMap<>();

        //测试 https://mdmuat.ganglongchina.com
        //测试 http://172.22.21.180:37080
        //生产 http://192.168.100.180
        JSONArray objects = new JSONArray();
        try {
            String deptList = HttpRequest.post("http://192.168.100.180/service/datapub/rest/api/v1/hcm/admorgList")
                    .header("appKey", "glyx")//头信息，多个头信息多次调用此方法即可
                    .header("appSecret", "eyJhbGciOiJIUzUxMiJ9.eyJhcHBDb2RlIjoiZ2x5eCIsImV4cCI6MTkyMzU0NDYwMH0.NKSJBNYg9BXtk9gHkbRfqkGCBK77dtEk33N-bLq6c6XQk8lsvVRGMlPzq0zdRvp9MFKkKB8xm-SJ_efdNMYyCg")//头信息，多个头信息多次调用此方法即可
                    .form(paramMap)//表单内容
                    .timeout(10000)//超时，毫秒
                    .execute().body();
            JSONObject result = JSONObject.parseObject(deptList);
            if(result.getString("code").equals("2000")){
                objects=result.getJSONArray("data");
                for (int i = 0; i < objects.size(); i++) {
                    JSONObject obj = objects.getJSONObject(i);
                    logger.info(obj.toJSONString());
                    SysDept org_code = sysDeptService.selectDeptById(obj.getString("org_code"));
                    if (org_code == null || StringUtils.isEmpty(org_code.getDeptId())) {

                        SysDept sysDept = new SysDept();
                        sysDept.setDeptId(obj.getString("org_code"));
                        sysDept.setDeptName(obj.getString("org_name"));
                        sysDept.setParentId(obj.getString("parent_org_code"));
                        sysDept.setLeader(obj.getString("enable_state"));
                        logger.debug("同步部门数据开始:"+sysDept.getDeptId()+"-"+sysDept.getDeptName()+"-"+sysDept.getParentId());
                        sysDeptService.insertDept(sysDept);
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error("查询所有部门出错:"+e.getMessage());
        }finally {
            return objects;
        }

    }
    @Override
    public JSONArray getTxAllDeptList() {
        logger.info("同步腾讯邮箱部门数据开始:");
        JSONArray objects = new JSONArray();
        try {
            String qqEmailToken = this.getQqEmailToken();
            String deptList = HttpUtil.get("https://api.exmail.qq.com/cgi-bin/department/list?access_token="+qqEmailToken);
            JSONObject result = JSONObject.parseObject(deptList);
            if(result.getString("errcode").equals("0")){
                logger.debug("同步腾讯邮箱部门成功:");
                objects=result.getJSONArray("department");
                for (int i = 0; i < objects.size(); i++) {
                    JSONObject obj = objects.getJSONObject(i);
                    logger.info(obj.toJSONString());
                    SysDept org_code = sysDeptService.selectDeptById(obj.getString("id"));
                    if (org_code == null || StringUtils.isEmpty(org_code.getDeptId())) {
                        SysDept sysDept = new SysDept();
                        sysDept.setDeptId(obj.getString("id"));
                        sysDept.setDeptName(obj.getString("name"));
                        sysDept.setParentId(obj.getString("parentid"));
                        logger.debug("同步邮箱部门数据开始:"+sysDept.getDeptId()+"-"+sysDept.getDeptName()+"-"+sysDept.getParentId());
                        sysDeptService.insertDept(sysDept);
                    }
                }
                return objects;
            }else{
                logger.debug("同步腾讯邮箱部门失败");
                return null;
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error("查询所有部门出错:"+e.getMessage());
        }finally {
            return objects;
        }

    }
    @Override
    public void syncStart(int offset){
        JSONArray hrUserList = syncEmailsService.getHrUserList(offset);
        logger.info("有过修改的hr系统用户:"+hrUserList.toJSONString());
        if(hrUserList.size()>0){
            syncEmailsService.checkQqEmailInfo(hrUserList);
        }
        else{
            logger.debug("最近5分钟没有修改的hr数据:");
        }
    }

    @Override
    public void deleteEmailsStart(int offset){
        SysEmail sysEmail = new SysEmail();
        String token = this.getQqEmailToken();
        List<SysEmail> sysEmails = sysEmailService.selectSysEmailList(sysEmail);
        for (SysEmail email : sysEmails) {
            long between = DateUtil.between(email.getUpdateDate(), new Date(), DateUnit.DAY);
            if(between>offset||offset==0){
                syncEmailsService.deleteQqEmailInfo(token, email.getEmailId());
            }
        }
    }
    public static String insertQqEmailDeparmentInfo(String token,JSONObject jsonObject){

        logger.info("创建腾讯企业邮箱开始:"+jsonObject);
        String result2 = HttpRequest.post("https://api.exmail.qq.com/cgi-bin/department/create?access_token="+token)
                .body(jsonObject.toJSONString())
                .execute().body();

        JSONObject result = JSONObject.parseObject(result2);
        if(result.getString("errcode").equals("0")){
            logger.info("创建腾讯企业邮箱结束:"+result2);
        }else{
            logger.error("创建腾讯企业邮箱出错"+result2);
        }
        return result2;
    }
    public static void main(String[] args) {
//        JSONObject deparment = new JSONObject();
//        String qqEmailToken = "XeeHCETSJwYZ1yY655JX3lpdiMAdi_PTv_O7e3XUvtIcJma0pCfMvnm1p5bpdtESZzaIVo5jNPrGvhAHedUhsA";
//        deparment.put("access_token",qqEmailToken);
//        deparment.put("name","新用户");
//        deparment.put("parentid",1L);
//        deparment.put("order",0L);
//        SyncEmailsServiceImpl.insertQqEmailDeparmentInfo(qqEmailToken, deparment);
//        SyncEmailsServiceImpl.getHrAllDeptList2();
        logger.debug("最近5分钟没有修改的hr数据:");
    }

}
